package com.dlc.shop.multishop.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dlc.shop.bean.dto.UploadSuccessDTO;
import com.dlc.shop.bean.model.AttachFile;
import com.dlc.shop.bean.vo.PreSignUrlVO;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.PageParam;
import com.dlc.shop.config.ShopConfig;
import com.dlc.shop.security.multishop.util.SecurityUtils;
import com.dlc.shop.service.AttachFileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 文件上传 controller
 * @author lgh
 *
 */
@RestController
@RequestMapping("/admin/file")
@Tag(name = "上传文件记录接口")
@AllArgsConstructor
public class FileController {

    private final AttachFileService attachFileService;
    private final ShopConfig shopConfig;

    @GetMapping("/attachFilePage")
    @Operation(summary = "根据参数分页获取文件记录列表" , description = "根据参数分页获取文件记录列表")
    @PreAuthorize("@pms.hasPermission('admin:file:page')")
    public ServerResponseEntity<IPage<AttachFile>> attachFilePage(PageParam<AttachFile> page, AttachFile attachFile) {
        attachFile.setShopId(SecurityUtils.getShopUser().getShopId());
        IPage<AttachFile> attachFilePage = attachFileService.getPage(page,attachFile);
        return ServerResponseEntity.success(attachFilePage);
    }

    @DeleteMapping("/deleteFile/{fileId}")
    @Operation(summary = "根据文件记录id删除文件" , description = "根据文件记录id删除文件")
    @PreAuthorize("@pms.hasPermission('admin:file:delete')")
    public ServerResponseEntity<Void> deleteFile(@PathVariable("fileId") Long fileId){
        AttachFile attachFile = attachFileService.getById(fileId);
        if (Objects.isNull(attachFile)) {
            return ServerResponseEntity.success();
        }
        if (!Objects.equals(attachFile.getShopId(), SecurityUtils.getShopUser().getShopId())) {
            throw new YamiShopBindException("当前文件不属于你的店铺");
        }
        attachFileService.deleteFile(attachFile.getFilePath());
        return ServerResponseEntity.success();
    }

    @PutMapping("/updateFile")
    @Operation(summary = "更改文件记录信息" , description = "更改文件记录信息")
    @PreAuthorize("@pms.hasPermission('admin:file:update')")
    public ServerResponseEntity<Boolean> updateFile(@RequestBody AttachFile attachFile) {
        if (Objects.isNull(attachFile.getFileName())){
            // 图片名称不能为空
            throw new YamiShopBindException("yami.img.name.exist");
        }
        attachFile.setShopId(SecurityUtils.getShopUser().getShopId());
        return ServerResponseEntity.success(attachFileService.updateFile(attachFile));
    }

    @DeleteMapping("/deleteByIds")
    @Operation(summary = "根据文件id列表批量删除文件记录" , description = "根据文件id列表批量删除文件记录")
    @PreAuthorize("@pms.hasPermission('admin:file:delete')")
    public ServerResponseEntity<Void> deleteByIds(@RequestBody List<Long> ids) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        attachFileService.deleteByIdsAndShopId(ids, shopId);
        return ServerResponseEntity.success();
    }

    @PutMapping("/batchMove")
    @PreAuthorize("@pms.hasPermission('admin:file:update')")
    @Operation(summary = "根据文件id列表与分组id批量移动文件" , description = "根据文件id列表与分组id批量移动文件")
    public ServerResponseEntity<Void> batchMove(@RequestBody AttachFile attachFile) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        attachFileService.batchMoveByShopIdAndIdsAndGroupId(shopId, attachFile);
        return ServerResponseEntity.success();
    }

    @GetMapping("/get_file_by_id")
    @Operation(summary = "根据文件id获取文件信息")
    @PreAuthorize("@pms.hasPermission('admin:file:info')")
    public ServerResponseEntity<AttachFile> getFileById(@RequestParam("fileId") Long fileId){
        AttachFile attachFile = attachFileService.getById(fileId);
        Long shopId = SecurityUtils.getShopUser().getShopId();
        if (!Objects.equals(shopId,attachFile.getShopId())){
            throw new YamiShopBindException("yami.file.isNot.shop");
        }
        return ServerResponseEntity.success(attachFile);
    }

    @GetMapping("/getPreSignUrl")
    @Parameters({
            @Parameter(name = "fileName", description = "文件名"),
            @Parameter(name = "isImFile", description = "是否为客服聊天文件")
    })
    @Operation(summary = "获取预签名url(s3协议)")
    public ServerResponseEntity<PreSignUrlVO> getPreSignUrl(String fileName, Boolean isImFile) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        PreSignUrlVO preSingUrlVO = attachFileService.getPreSingUrl(shopId, fileName, isImFile);
        return ServerResponseEntity.success(preSingUrlVO);
    }

    @GetMapping("/getBatchPreSignUrl")
    @Parameters({
            @Parameter(name = "fileNames", description = "文件名集合"),
            @Parameter(name = "isImFile", description = "是否为客服聊天文件")
    })
    @Operation(summary = "批量获取预签名url(s3协议)")
    public ServerResponseEntity<List<PreSignUrlVO>> getBatchPreSignUrl(List<String> fileNames, Boolean isImFile) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        List<PreSignUrlVO> preSignUrlVOList = attachFileService.getBatchPreSignUrl(shopId, fileNames, isImFile);
        return ServerResponseEntity.success(preSignUrlVOList);
    }

    @PutMapping("/uploadSuccess")
    @Operation(summary = "上传成功(s3协议)(图片上传完调用此接口)")
    public ServerResponseEntity<Void> uploadSuccess(@RequestBody List<UploadSuccessDTO> uploadSuccessDTOList) {
        // 图片上传由前端完成，需要前端上传完图片后调用此接口，来修改数据库数据
        attachFileService.uploadSuccess(uploadSuccessDTOList);
        return ServerResponseEntity.success();
    }

    @PutMapping("/uploadSuccessToPlatform")
    @Operation(summary = "上传成功(保存至平台端)")
    public ServerResponseEntity<Void> uploadSuccessToPlatform(@RequestBody List<UploadSuccessDTO> uploadSuccessDTOList) {
        for (UploadSuccessDTO uploadSuccessDTO : uploadSuccessDTOList) {
            uploadSuccessDTO.setShopId(Constant.PLATFORM_SHOP_ID);
        }
        attachFileService.uploadSuccess(uploadSuccessDTOList);
        return ServerResponseEntity.success();
    }
}
